<template>
  <div class="login-wrapper">
    <el-row>
      <!-- 24  -->
      <el-col :span="8"></el-col>
      <el-col style="margin-top: 250px" :span="8">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="账号" prop="username">
            <el-input
              v-model="ruleForm.username"
              type="text"
              autocomplete="off"
            />
          </el-form-item>

          <el-form-item label="密码" prop="pass">
            <el-input v-model.number="ruleForm.pass" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)"
              >Submit</el-button
            >
            <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8"></el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'

const router = useRouter()

const ruleFormRef = ref<FormInstance>()

const validateUserName = (rule: any, value: any, callback: any) => {
  // console.log('validateUserName:', rule)
  if (value === '') {
    callback(new Error('Please input the username again'))
  } else {
    callback()
  }
}

const validatePass = (rule: any, value: any, callback: any) => {
  // console.log('validatePass:', rule)
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    if (ruleForm.pass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}

const ruleForm = reactive({
  username: '',
  pass: ''
})

const rules = reactive({
  username: [{ validator: validateUserName, trigger: 'blur' }],
  pass: [{ validator: validatePass, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    console.log(valid, 'valid')
    if (valid) {
      router.push('/basic/home')
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
